package com.xiangxiangjd.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.Goods;
import com.xiangxiangjd.bean.HandoverGoods;
import com.xiangxiangjd.bean.Unit;
import com.xiangxiangjd.bean.vo.HandoverDocx;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.bean.HandoverDateNo;
import com.xiangxiangjd.mapper.HandoverDateNoMapper;
import com.xiangxiangjd.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangxiangjd.bean.result.ResultPage;
import com.xiangxiangjd.controller.model.ApiResultModel;

import com.xiangxiangjd.utils.OddNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 申领航材批次号 服务实现类
 *
 * @author 肖守凯
 * @since 2021-11-08
 */
@Service
public class HandoverDateNoServiceImpl extends ServiceImpl<HandoverDateNoMapper, HandoverDateNo>
    implements HandoverDateNoService {
  // 交接和物品的中间表
  @Autowired HandoverGoodsService handoverGoodsService;

  @Autowired GoodsService goodsService;


  // 处置的物品
  @Autowired private UnitService unitService;

  @Autowired private TrUserService trUserService;

  @Autowired private DateNoService dateNoService;

  /**
   * 添加HandoverDateNo
   *
   * @param handoverDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Transactional(isolation = Isolation.READ_COMMITTED)
  @Override
  public ApiResultModel addHandoverDateNo(HandoverDateNo handoverDateNo) {

    handoverDateNo.setHandoverDateNoState("0");

    // 查询最后一次生成的单号
    String handoverOddNumber = baseMapper.getLastHandoverOddNumber();

    handoverDateNo.setHandoverOddNumber(OddNumber.getOddNumber("JJ", handoverOddNumber));
    // 保存单号
    if (!this.saveOrUpdate(handoverDateNo)) {
      throw new RuntimeException("交接失败");
    }
    // 所有交接航材
    List<HandoverGoods> handoverGoodsList = handoverDateNo.getHandoverGoodsList();

    List<HandoverGoods> collect =
        handoverGoodsList.stream()
            .map(
                o -> {
                  o.setHandoverId(handoverDateNo.getId());
                  return o;
                })
            .collect(Collectors.toList());

    boolean b = handoverGoodsService.saveOrUpdateBatch(collect);
    if (!b) {
      throw new RuntimeException("交接失败");
    }

    return $.success("交接成功 等待确认接收");
  }
  /**
   * 编辑跳转页面的回显数据HandoverDateNo
   *
   * @param id 前端传进的参数
   * @return 返回实体类
   */
  @Override
  public HandoverDateNo selectHandoverDateNoByIdHandoverDateNo(String id) {
    return this.getById(id);
  }

  /**
   * 编辑HandoverDateNo
   *
   * @param handoverDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel editHandoverDateNo(HandoverDateNo handoverDateNo) {
    if (this.updateById(handoverDateNo)) {
      return $.success();
    } else {
      return $.error("编辑失败");
    }
  }
  /**
   * 删除一条HandoverDateNo
   *
   * @param ids 前端传进的ID
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel delHandoverDateNos(List ids) {

    int i = baseMapper.deleteBatchIds(ids);

    return $.success(i);
  }

  /**
   * 分页查询HandoverDateNo
   *
   * @param page 页码
   * @param limit 查几条
   * @param handoverDateNo 前端传进的参数
   * @return 返回统一分页信息
   */
  @Override
  public ResultPage findHandoverDateNoByPage(
      Integer page, Integer limit, HandoverDateNo handoverDateNo) {
    Map<String, Object> paramMap = new HashMap<>();
    page = page == null ? 1 : page;
    limit = limit == null ? 20 : limit;

    paramMap.put("page", (page - 1) * limit);
    paramMap.put("limit", limit);
    paramMap.put("handoverDateNo", handoverDateNo);
    List<HandoverDateNo> list = baseMapper.selectMyPage(paramMap);
    Integer count = baseMapper.countMyPage(paramMap);
    ResultPage<HandoverDateNo> resultPage = new ResultPage<>();
    resultPage.setCode(200);
    resultPage.setCount(count);
    resultPage.setMsg("成功");
    resultPage.setData(list);
    return resultPage;
  }

  /**
   * 交接审批
   *
   * @param
   * @param claimdateNoState
   * @return
   */
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  @Override
  public ApiResultModel handoverApproval(Integer handoverDateNoId, String claimdateNoState,String reasonForFfailure,String handoverApprovalUserId) {
    // 修改状态
    boolean update =
        this.update(
            new LambdaUpdateWrapper<HandoverDateNo>()
                .set(HandoverDateNo::getHandoverDateNoState, claimdateNoState)
                    .set(HandoverDateNo::getReasonForFailure,reasonForFfailure)
                    .set(HandoverDateNo::getHandoverApprovalUserId,handoverApprovalUserId)
                .eq(HandoverDateNo::getId, handoverDateNoId));

    // 审批通过修改
    if (claimdateNoState.equals("3")) {
      // 查询所有要交接的航材
      List<HandoverGoods> handoverGoodsList =
          handoverGoodsService.list(
              new LambdaQueryWrapper<HandoverGoods>()
                  .eq(HandoverGoods::getHandoverId, handoverDateNoId));
      // 查询交接单号信息
      HandoverDateNo handoverDateNo = this.getById(handoverDateNoId);

      // 单件循环 验证交接
      for (HandoverGoods handoverGoods : handoverGoodsList) {

        // 开始交接
        boolean update1 = goodsService.update(
                new LambdaUpdateWrapper<Goods>()
                        .set(Goods::getUserId, handoverDateNo.getHandoverUsersId())
                        .eq(Goods::getUserId, handoverDateNo.getUserId())
                        .eq(Goods::getGoodsType, "1")
                        .eq(Goods::getId,handoverGoods.getGoodsId())
        );
        if(!update1){
          throw new RuntimeException("该航材已交接 或者已归还："+handoverGoods.getGoodsId());
        }

      }

    }

    return $.success("成功 改变状态");
  }

  @Override
  public ApiResultModel getByHandover(Integer handoverDateNoId) {
    HandoverDateNo handoverDateNo =baseMapper.getByHandover(handoverDateNoId);

    return $.success(handoverDateNo);
  }

  @Override
  public Map downDocHandoverDateNo(Integer handoverDateNoId) {


    HandoverDateNo handoverDateNo =baseMapper.getByHandover(handoverDateNoId);

    if(handoverDateNo==null){
      throw new RuntimeException("交接订单 不可为 空");
    }

    //获取所有要交接的物品
    List<HandoverGoods> handoverGoodsList = handoverDateNo.getHandoverGoodsList();

    if(handoverGoodsList==null){
      throw new RuntimeException("没有交接物品");
    }

    List<HandoverDocx> handoverDocxList=new ArrayList<>();

    int i=0;

    /**
     * 判断相同的物品进行累计
     */
    for (HandoverGoods handoverGoods : handoverGoodsList) {

      HandoverDocx handoverDocx = new HandoverDocx();

      handoverDocx.setSerialNumber(++i);
      handoverDocx.setGoodsId(handoverGoods.getGoodsId());
      handoverDocx.setGoodsName(handoverGoods.getGoodsName());
      handoverDocx.setModel(handoverGoods.getModel());

      // 状态
      handoverDocx.setStatus("无");

      // 数量
      handoverDocx.setNumber(1.0);


      handoverDocx.setPrice(Double.valueOf(handoverGoods.getPrice()));

      handoverDocx.setTotalPrice( Double.valueOf(handoverGoods.getPrice()));

      handoverDocxList.add(handoverDocx);
    }




   Map map =new HashMap();

    map.put("data",handoverDocxList);

  //接收单位
    Unit handoverUnit = unitService.getById(handoverDateNo.getHandoverUnitId());

    map.put("handoverUnitName",handoverUnit.getUnitName());
//交付单位
    Unit unit = unitService.getById(handoverDateNo.getUnitId());
    map.put("unitName",unit.getUnitName()); //委托人

    return map;
  }
}
